﻿using System.Linq;

namespace Borg.Framework
{
    internal static class StateHelper
    {
        internal static SlotState GetSlotState(SlotInfo slot)
        {
            if (slot.IsOpen)
                return SlotState.Open;

            return slot.SlotTypeInfo.IsQualified
                ? SlotState.Qualified
                : SlotState.Discovered;
        }

        internal static State GetState(ExtensionInfo ext)
        {
            var discovered = State.Discovered;

            if (ext.Id == 1)
                return State.Plugged;

            foreach (var pi in ext.PlugInfos)
            {
                var state = GetState(pi);

                if (state > discovered)
                    discovered = state;
            }

            return discovered;
        }

        internal static State GetState(ExtensionTypeInfo extType)
        {
            State state;
            var discovered = State.Discovered;
            
            if (extType.ExtensionInfos.Count == 0)
            {
                foreach (var pti in extType.PlugTypeInfos)
                {
                    state = GetState(pti);

                    if (state > discovered)
                        discovered = state;
                }

                return discovered;
            }

            foreach (var ei in extType.ExtensionInfos)
            {
                state = GetState(ei);

                if (state > discovered)
                    discovered = state;
            }

            return discovered;
        }

        internal static State GetState(PlugInfo plug)
        {
            return plug.PluggedInSlots.Any(si => si.SelectedPlugs.Contains(plug))
                       ? State.Selected
                       : (plug.PluggedInSlots.Count > 0
                              ? State.Plugged
                              : (plug.PlugTypeInfo.RegisteredInSlots.Count > 0
                                     ? State.Registered
                                     : (plug.PlugTypeInfo.IsQualified
                                            ? State.Qualified
                                            : State.Discovered)));
        }

        internal static State GetState(PluginInfo plugin)
        {
            var discovered = State.Discovered;
            
            foreach (var eti in plugin.ExtensionTypeInfos)
            {
                var state = GetState(eti);

                if (state > discovered)
                    discovered = state;
            }

            return discovered;
        }

        internal static State GetState(PlugTypeInfo plugType)
        {
            return plugType.RegisteredInSlots.Count > 0
                       ? State.Registered
                       : (plugType.IsQualified
                              ? State.Qualified
                              : State.Discovered);
        }
    }
}

